package db

import (
	"errors"
	"strconv"
	"strings"
)

// DbMailConfig 全服邮件
type DbMailConfig struct {
	Id         uint64          `gorm:"column:id;type:bigint(20);primaryKey;autoIncrement"` // 全服邮件自增id
	Title      string          `gorm:"column:title;type:text"`                             // 邮件标题
	Content    string          `gorm:"column:content;type:text"`                           // 邮件内容
	Sender     string          `gorm:"column:sender;type:text"`                            // 邮件发送者
	SendTime   uint32          `gorm:"column:send_time;type:int(11)"`                      // 邮件发送时间戳 秒
	ExpireTime uint32          `gorm:"column:expire_time;type:int(11)"`                    // 邮件过期时间戳 秒
	ItemList   string          `gorm:"column:item_list;type:text"`                         // 道具列表
	ItemMap    map[int32]int32 `gorm:"-"`
}

func (mc *DbMailConfig) TableName() string {
	return "gm_mail_config"
}

func GetMailConfigWhereIdGt(id uint64) ([]*DbMailConfig, error) {
	var mailConfigList []*DbMailConfig = nil
	err := Conn.Where("id > ?", id).Find(&mailConfigList).Order("id ASC").Error
	if err != nil {
		return nil, err
	}
	for _, mailConfig := range mailConfigList {
		mailConfig.ItemMap = make(map[int32]int32)
		if mailConfig.ItemList == "" {
			continue
		}
		for _, item := range strings.Split(mailConfig.ItemList, "|") {
			split := strings.Split(item, ",")
			if len(split) != 2 {
				return nil, errors.New("mail item list format error")
			}
			itemId, err := strconv.Atoi(split[0])
			if err != nil {
				return nil, err
			}
			count, err := strconv.Atoi(split[1])
			if err != nil {
				return nil, err
			}
			mailConfig.ItemMap[int32(itemId)] += int32(count)
		}
	}
	return mailConfigList, nil
}
